
import { Provide, Inject } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { TeacherDao } from '../dao/teacher.dao';
import { CreateTeacherDto, UpdateTeacherDto, QueryTeacherDto } from '../dto/teacher.dto';
import { ExitTeamDto } from '../dto/team.dto';
import { DownloadExcelService } from '../service/common/downloadExcel';
import { ImportExcelDTO } from '@dto/common/excel.dto';
import { ResolveExcelService } from '@service/common/resolveWebExcel';
import { StudentTeamEntity } from '@entity/studentTeam.entity';
import { MidwayError } from '@midwayjs/core';

@Provide()
export class TeacherService {
  @Inject()
  teacherDao: TeacherDao;
  @Inject()
  downloadExcelService: DownloadExcelService;
  @Inject()
  resolveExcelService: ResolveExcelService;
  @InjectEntityModel(StudentTeamEntity)
  studentTeamRepo: Repository<StudentTeamEntity>;
  // 创建
  async create(body: CreateTeacherDto) {
    return await this.teacherDao.create(body);
  }
  // 获取列表
  async list(query: QueryTeacherDto) {
    return await this.teacherDao.list(query);
  }

  // 根据学院ID获取教师列表
  async listByDept(deptId: number) {
    return await this.teacherDao.listByDept(deptId);
  }
  // 获取详情
  async detail(teacherId: string) {
    return await this.teacherDao.detail(+teacherId);
  }
  // 修改
  async update(body: UpdateTeacherDto) {
    return await this.teacherDao.update(body);
  }
  // 删除
  async remove(teacherIds: Array<number>) {
    return await this.teacherDao.remove(teacherIds);
  }
  // 导出
  async export(queryParams: QueryTeacherDto) {
    const headers = [
      { label: '教师ID', prop: 'teacherId' },
      { label: '用户ID', prop: 'userId' },
      { label: '工号', prop: 'teachId' },
      { label: '邮箱', prop: 'email' },
      { label: '个人简介', prop: 'summary' },
      { label: '专业方向', prop: 'majorField' },
      { label: '备注', prop: 'remark' },
      { label: '状态（0正常 1停用）', prop: 'status' }
    ];
    const { rows } = (await this.teacherDao.list(queryParams)).data;
    return this.downloadExcelService.downloadExcel({
      headers,
      data: rows,
      sheetName: 'Teacher信息',
    });
  }
  async importTemplate() {
    return await this.downloadExcelService.downloadExcel({
      headers: [
        { label: '工号', prop: 'teachId' },
        { label: '姓名', prop: 'nickName' },
        { label: '学院（如：生物医学工程学院）', prop: 'dept' },
        { label: '邮箱', prop: 'email' },
        { label: '手机号', prop: 'phonenumber' },
        { label: '专业方向', prop: 'majorField' },
        { label: '个人简介', prop: 'summary' },
      ],
      data: [],
      sheetName: 'Teacher模板',
    });
  }

  // 导入数据
  async importData(body: ImportExcelDTO) {
    const { files, updateSupport } = body;

    // 1.解析Excel文件
    const result = await this.resolveExcelService.resolvedWebExcelStream(files);
    const { tableData } = result;

    if (!tableData || tableData.length === 0) {
      throw new Error('导入数据为空');
    }

    // 2.获取学院列表，构建查找Map
    const deptMap = await this.buildDeptMap();

    // 3.转换Excel数据为实体对象
    const teachers = [];
    const errors = [];

    for (let i = 0; i < tableData.length; i++) {
      try {
        const row = tableData[i];
        // Excel列: [工号, 姓名, 学院, 邮箱, 手机号, 专业方向, 个人简介]
        const [teachId, nickName, deptName, email, phonenumber, majorField, summary] = row;

        // 验证必填字段
        if (!teachId) {
          errors.push(`第${i + 2}行：工号不能为空`);
          continue;
        }
        if (!nickName) {
          errors.push(`第${i + 2}行：姓名不能为空`);
          continue;
        }

        // 查找学院ID
        const dept = deptMap.get(deptName?.trim());
        if (!dept) {
          errors.push(`第${i + 2}行：学院"${deptName}"不存在`);
          continue;
        }

        // 构建教师数据对象
        teachers.push({
          teachId: String(teachId).trim(),
          nickName: String(nickName).trim(),
          deptId: dept.deptId,
          email: email ? String(email).trim() : '',
          phonenumber: phonenumber ? String(phonenumber).trim() : '',
          majorField: majorField ? String(majorField).trim() : '',
          summary: summary ? String(summary).trim() : '',
          status: '0',
        });
      } catch (error) {
        errors.push(`第${i + 2}行：数据解析失败 - ${error.message}`);
      }
    }

    // 4.如果有错误，返回错误信息
    if (errors.length > 0) {
      throw new Error(`导入失败，共${errors.length}条错误：\n${errors.join('\n')}`);
    }

    // 5.批量导入数据（使用事务）
    const results = await this.teacherDao.batchImport(teachers, updateSupport);

    return {
      success: true,
      message: `导入完成！成功${results.successCount}条，失败${results.failCount}条`,
      data: results,
    };
  }

  /**
   * 构建学院查找Map
   */
  private async buildDeptMap() {
    const { SysDept } = await import('@entity/framework/system/SysDept');


    // 直接通过 DAO 获取学院列表
    const deptList = await this.teacherDao.userRepo.manager
      .getRepository(SysDept)
      .createQueryBuilder('dept')
      .where('dept.delFlag = :delFlag', { delFlag: '0' })
      .andWhere('dept.deptName LIKE :deptName', { deptName: '%学院%' })
      .select(['dept.deptId', 'dept.deptName'])
      .getMany();

    // 学院Map: deptName -> { deptId, deptName }
    const deptMap = new Map();
    for (const dept of deptList) {
      deptMap.set(dept.deptName, {
        deptId: dept.deptId,
        deptName: dept.deptName,
      });
    }

    return deptMap;
  }

  /**
   * 学生退出队伍
   * @param body - 包含 teamId 和 studentId 的退出队伍数据
   */
  async exitTeam(body: ExitTeamDto) {
    const { teamId, studentId } = body;

    // 1. 查询学生-队伍关联记录是否存在
    const studentTeam = await this.studentTeamRepo.findOne({
      where: {
        teamId,
        studentId,
      },
    });

    if (!studentTeam) {
      throw new MidwayError(`学生(ID:${studentId})不在队伍(ID:${teamId})中`, '404');
    }

    // 2. 删除学生-队伍关联记录
    await this.studentTeamRepo.delete({
      teamId,
      studentId,
    });

    return {
      success: true,
      message: '学生已成功退出队伍',
      data: {
        teamId,
        studentId,
      },
    };
  }
}